package com.hsnn.medstgmini.base.dict.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicSys;
import com.hsnn.medstgmini.base.dict.model.DicSysDicLog;
import com.hsnn.medstgmini.base.dict.service.DicDrugformManager;
import com.hsnn.medstgmini.base.dict.service.DicSysManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 自定义字典
 * @author 张俊
 */
@Controller
@RequestMapping("/dicSys")
public class DicSysController {
	
	private static final Logger log = Logger.getLogger(DicPharController.class);
	
	@Autowired
	private DicSysManager dicSysManager;
	

	@Autowired
	private HttpServletRequest request;
	
	/**
	 * @category 跳转自定义字典列表页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/dicSysList")
	public String  dicSysList() {
		log.info("enter dicSysList method!");
		return "/base/dict/sysList";
	}
	
	/**
	 * @category 查询自定义字典列表
	 * @param result
	 * @param dicSys
	 * @return
	 */
	@RequestMapping("/getDicSysList")
	@ResponseBody
	public Pagination getDicSysList() {
		log.info("enter getDicSysList method!");
		 printParams();
		Pagination  page = new Pagination(request);
		page.getConditions().put("classifyCode", request.getParameter("classifyCode"));
		page.getConditions().put("classifyName", request.getParameter("classifyName"));
		page.getConditions().put("dicCode", request.getParameter("dicCode"));
		page.getConditions().put("dicName", request.getParameter("dicName"));
		page.getConditions().put("status", request.getParameter("status"));
		try {
			dicSysManager.getDicSysList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	

	
	

	/**
	 * @category 查询待编辑记录
	 * @param id
	 * @param selfId
	 * @return
	 */
	@RequestMapping("/initEdit")
	@ResponseBody
	public Pagination initEdit(String id, String selfId) {
		 printParams();
		Pagination page = new Pagination(request);
		try {
			page.setRows(dicSysManager.getDicSysById(id));
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}


	/**
	 * @category 批量(启用|停用)
	 * @param array
	 * @return
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(String array) {
		 printParams();
		Pagination page = new Pagination(request);
		try {
			SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<DicSys>>() {
				}.getType();
				List<DicSys> list = gson.fromJson(array, type);
				if (list != null && !list.isEmpty()) {
					for (DicSys sd : list) {
						sd.setUpdUser(user.getId());
					}
					int sum = dicSysManager.batchChangeStatus(list);
					page.getConditions().put("sum", sum+"");
					page.setSuccess(true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}


	/**
	 * @category 跳转到自定义字典维护记录列表页面
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/log")
	public String dicPharLogList(Model model, String id) {
		 printParams();
		model.addAttribute("id", id);
		request.setAttribute("dicCode", request.getParameter("dicCode"));
		try {
			String dicName = new String(request.getParameter("dicName").getBytes("iso8859-1"),"utf-8");
			request.setAttribute("dicName", dicName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "/base/dict/sysDicLogList";
	}

	/**
	 * @category 查询自定义字典维护记录列表
	 * @param result
	 * @param sysDicLog
	 * @return
	 */
	@RequestMapping("/getDicSysDicLogList")
	@ResponseBody
	public Pagination getDicPharLogList(DicSysDicLog dicSysDicLog) {
		 printParams();
		Pagination page = new Pagination(request);
		try {
			if (dicSysDicLog != null) {
				List<DicSysDicLog> list = dicSysManager.getDicSysDicLogList(page, dicSysDicLog);
				page.setRows(list);
				page.setSuccess(true);
			}
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	
	/**
	 * 跳转到  基础库 系统字典  维护日志 页面
	 * @param result  getSysDicLogList
	 * @return
	 */
	 	@RequestMapping("/toSysDicLogList")
		public String  toSysDicLogList() {
			log.info("enter toDicPackunitLogList method!");
			 printParams();
			request.setAttribute("sysDicId", request.getParameter("sysDicId"));
			return "/base/dict/sysDicLogList";
		}
	 	//获取 基础库 系统字典  维护日志 列表
	 	@RequestMapping("/getSysDicLogList")
		@ResponseBody
		public Pagination  getSysDicLogList(){
			log.info("enter getSysDicLogList method!");
			 printParams();
			Pagination  page = new Pagination(request);
			page.getConditions().put("startTime", request.getParameter("startTime"));
			page.getConditions().put("endTime", request.getParameter("endTime"));
			page.getConditions().put("sysDicId", request.getParameter("sysDicId"));
			try {
				dicSysManager.getSysDicLogList(page);
				page.setSuccess(true);
			} catch (Exception e) {
				e.printStackTrace();
				page.setSuccess(false);
			}
			return page;
		}
	 	
	 	
	
	
	
	/**
	 * 基础库 系统在字典  日志详情
	 * @param result
	 * @return
	 */
	@RequestMapping("/toDicSysDicLogListDetail")
	public String toDicSysDicLogListDetail(){
		log.info("enter toDicSysDicLogListDetail method!");
		 printParams();
		Pagination  page = new Pagination();
		page.getConditions().put("logId", request.getParameter("logId"));
		List<Map<String,Object>> list = dicSysManager.getDicSysDicLogListDetail(page);
		
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		String[] cColunm = {"字典分类编码","字典分类名称","字典编码","字典内容","备注","状态"};
		String[] eColunm = {"classifyCode","classifyName","dicCode","dicName","remark","status"};
		for(int i = 0;i<cColunm.length;i++){
			Map<String,Object> map =  new HashMap<String,Object>();
			map.put("colunm", cColunm[i]);//字段名
			map.put("after", !"status".equals(eColunm[i])?list.get(0).get(eColunm[i]):"1".equals(list.get(0).get(eColunm[i]).toString())?"启用":"停用");//修改后数据
			map.put("before", list.size()==1?null:!"status".equals(eColunm[i])?list.get(1).get(eColunm[i]):"1".equals(list.get(1).get(eColunm[i]).toString())?"启用":"停用");//修改前数据
			if(list.size()==1){
				map.put("red", "1");//是否变红加粗 1是 0 否
			}else{
				//判断修改后与修改前数据是否相等
				if(list.get(0).get(eColunm[i])!=null&&list.get(1).get(eColunm[i])!=null&&!list.get(0).get(eColunm[i]).toString().equals(list.get(1).get(eColunm[i]).toString())){
					map.put("red", "1");
				}else{
					map.put("red", "0");
				}
			}
			mapList.add(map);
		}
		for(int i = 0;i<mapList.size();i++){//把要变红的放在list前面
			if("1".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		for(int i = 0;i<mapList.size();i++){
			if("0".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		request.setAttribute("dataList", dataList);
		
		request.setAttribute("list", list);
		return "/base/dict/sysDicLogListDetail";
		
	}
	
	/**
	 * 自定义字典  新增和编辑
	 * @param dicSys
	 */
	@RequestMapping(value={"/add","/edit"},method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public Pagination dicSysAdd(HttpServletRequest request,HttpServletResponse response) {
		 printParams();
		Pagination page=new Pagination();
		SysUser user = (SysUser)request.getSession().getAttribute(Constants.USERINFO);
		DicSys dicSys = new DicSys();
		Date date = new Date();
		//Date ts = new Date(System.currentTimeMillis());  
        String classifyCode = request.getParameter("classifyCode").trim();//字典分类编码
        String classifyName = request.getParameter("classifyName").trim();//字典分类名称
        String dicCode = request.getParameter("dicCode").trim();//字典编码
        String dicName = request.getParameter("dicName").trim();//字典名称
        String sysDicId = request.getParameter("sysDicId");//字典id
        
        String status =request.getParameter("status");//状态
        String remark = request.getParameter("remark");//备注
        short number = (short) 1;
        try {  
            if(null != sysDicId && !"".equals(sysDicId)){
            	dicSys.setSysDicId(sysDicId);
            	DicSys data = dicSysManager.getDicSysById(sysDicId);
            	if(classifyCode.equals(data.getClassifyCode())&&classifyName.equals(data.getClassifyName())&&dicCode.equals(data.getDicCode())&&dicName.equals(data.getDicName())&&remark.equals(data.getRemark())){
            		page.setMsg("数据未做任何修改,不能保存!");
            		page.setSuccess(false);
            		return page;
            	}
            }
            if(null != status && !"".equals(status)){
            	dicSys.setStatus((short) Integer.parseInt(status));
            }else{
            	dicSys.setStatus((short) 1);
            }
            dicSys.setSortId(number);
            dicSys.setUpdDatetime(date);
            dicSys.setClassifyCode(classifyCode);
            dicSys.setClassifyName(classifyName);
            dicSys.setDicCode(dicCode);
            dicSys.setDicName(dicName);
            dicSys.setUpdUser(user.getId());
            dicSys.setUpdDatetime(new Date());
            dicSys.setRemark(remark);
            page.setForm(dicSys);
            if(StringUtils.isBlank(classifyCode)){
            	page.setMsg("请输入字典分类编码!");
            	page.setSuccess(false);
            	return page;
            }
            if(StringUtils.isBlank(classifyName)){
            	page.setMsg("请输入字典分类名称!");
            	page.setSuccess(false);
            	return page;
            }
            if(StringUtils.isBlank(dicCode)){
            	page.setMsg("请输入字典编码!");
            	page.setSuccess(false);
            	return page;
            }
            if(StringUtils.isNotBlank(dicName)){
            	List<DicSys> list=(List<DicSys>) dicSysManager.getDicSysBy("dicName", dicName, sysDicId);
            	 if(list.size()>0){
	            		 page.setMsg("字典名称已存在!");
	            		 page.setSuccess(false);
	            		 return page;
                 }
            }else{
            	page.setMsg("请输入字典名称!");
            	page.setSuccess(false);
            	return page;
            }
            dicSysManager.addAndEdit(page);
    		page.setMsg("保存成功!");
    		page.setSuccess(true);
        } catch (Exception e) {  
            e.printStackTrace(); 
            page.setMsg("保存失败!");
            page.setSuccess(false);
        }
		return page; 
	}
	/**
	 * @category 验证重复性
	 * @author zhouqi
	 * @param 
	 * @return
	 */
	@RequestMapping("/validateRep")
	@ResponseBody
	public String validateRep(){
		 printParams();
         String classifyCode = request.getParameter("classifyCode");
         String classifyName = request.getParameter("classifyName");
         
         Map<String,String> conditions = new HashMap<String, String>();
         if(StringUtils.isNotBlank(classifyCode)){
        	 conditions.put("classifyCode", classifyCode);
         }
         if(StringUtils.isNotBlank(classifyName)){
        	 conditions.put("classifyName", classifyName);
         }
         List<DicSys> list = dicSysManager.getSysDicByCondition(conditions);
         if(list.size() >0){
        	 return JSON.toJSONString(false);
         }
         return JSON.toJSONString(true);
	}
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
		
	}
	
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response){
		printParams();
		Pagination page = new Pagination();
		String sysDicId = request.getParameter("sysDicId");
		String classifyCode = request.getParameter("classifyCode");
		String classifyName = request.getParameter("classifyName");
		String dicCode  = request.getParameter("dicCode");
		String dicName  = request.getParameter("dicName");
		String remark  = request.getParameter("remark");
		String status = request.getParameter("status");
		String updDatetime = request.getParameter("updDatetime");
		String updUser = request.getParameter("updUser");
		String sortId = request.getParameter("sortId");
		if(StringUtils.isNotBlank(sysDicId)){
			page.getConditions().put("sysDicId", sysDicId.trim());
		}
		if(StringUtils.isNotBlank(classifyCode)){
			page.getConditions().put("classifyCode", classifyCode.trim());
		}
		if(StringUtils.isNotBlank(classifyName)){
			page.getConditions().put("classifyName", classifyName.trim());
		}
		if(StringUtils.isNotBlank(dicCode)){
			page.getConditions().put("dicCode", dicCode.trim());
		}
		if(StringUtils.isNotBlank(dicName)){
			page.getConditions().put("dicName", dicName.trim());
		}
		if(StringUtils.isNotBlank(remark)){
			page.getConditions().put("remark", remark.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		if(StringUtils.isNotBlank(updDatetime)){
			page.getConditions().put("updDatetime", updDatetime.trim());
		}
		if(StringUtils.isNotBlank(updUser)){
			page.getConditions().put("updUser", updUser.trim());
		}
		if(StringUtils.isNotBlank(sortId)){
			page.getConditions().put("sortId", sortId.trim());
		}
	
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String("系统字典.xls".getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			dicSysManager.exportExcel(page,os);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}
